package com.yaodong.encrypt.utils;

/**
 * Created
 * Author:lvyaodong[Darksider]
 * Email:1126220529@qq.com
 * Date:2015/10/16
 */

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
 * 1.实现在客户端（1）第一次运行时生成KeyPair然后保存在共享文件中下次在启动时 （2）自动加载 保存的KeyPair
 *
 * 2.对一端数据进行加密，加密后在编码成Base64 并且把公钥保存成Base64 ，然后再将两个数据组合 形成一个Json  用GZIP压缩流保存在文件中
 */
public class AutoRSAKeyPair{
    private  Context context;
    public AutoRSAKeyPair(Context context){
        this.context = context;
    }
    public  void saveKeyPair(String str){

        SharedPreferences sp = context.getSharedPreferences("KeyPair", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        int count = sp.getInt("count",0);
        if(count == 0){
            KeyPair keyPair = EncryptUtil.generateRSAKeyPair(1024);
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            byte[] publicKeyEncoded = publicKey.getEncoded();
            String publicKeyStr = Base64.encodeToString(publicKeyEncoded, Base64.NO_WRAP);
            byte[] privateKeyEncoded = privateKey.getEncoded();
            String privateKeyStr = Base64.encodeToString(privateKeyEncoded, Base64.NO_WRAP);
            editor.putString("publicKeyStr", publicKeyStr);
            editor.putString("privateKeyStr",privateKeyStr);
            editor.putInt("count",++count);
            editor.commit();
        }else{
            String sharePublicKeyStr = sp.getString("publicKeyStr", null);
            String sharePrivateKeyStr = sp.getString("privateKeyStr", null);

        }

    }

}
